<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge"></meta>
    <title>Document</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/socket.io/4.5.1/socket.io.js"></script>
  </head>
<body>
    <button id="connect">连接ws服务器</button>
    <input type="text" id="msg">
    <button type="button" id="btn">发送</button>
    <p id="response"></p>

    <script>
      let socket
      document.getElementById('connect').onclick = () => {
        // 连接ws服务器, 得到连接对象
        socket = io('ws://localhost:4000')
        // 绑定监听 orderStatus, 接收服务器发送过来的消息
        socket.on('orderStatus', (data) => {
          alert(data.status)
        })

        // 绑定接收服务器返回消息的监听
        socket.on('backMsg', (msg) => {
          document.getElementById('response').innerHTML = msg
        })
      }

      // 绑定发送聊天消息的点击事件
      document.getElementById('btn').addEventListener('click', function() {
        const msg = document.getElementById('msg').value
        socket.emit('sendMsg', msg)
      })
    </script>
</body>
</html>
